I have a raw pointer pointing to a memory address. I want to assign this address to a std::shared_ptr
. I did a test project which does it successfully. However, in my main project I cannot replicate the same.
This is my test project:
#include <cassert>
#include <memory>
struct A {
int a = 0;
float b = 0.0f;
};
int main()
{
A* pa = new A;
pa->a = 123;
pa->b = 0.1f;
std::shared_ptr<A> spa;
assert(spa == nullptr); // set to `nullptr` during construction
spa.reset(pa);
assert(spa != nullptr);
assert(spa->a == 123);
assert(spa->b < 1.0);
return 0;
}
This is the CMakeList.txt
file:
cmake_minimum_required (VERSION 3.23)
project ("PtrToShPtr")
add_executable (PtrToShPtr "PtrToShPtr.cpp" )
set_property(TARGET PtrToShPtr PROPERTY CXX_STANDARD 20)
While this project builds without issues, my main one (with very similar code) generates a compile time error; this is the code:
struct XMLDoc {
tinyxml2::XMLElement* createElement() {
return new tinyxml2::XMLElement;
}
};
...
XMLDoc xmlDoc;
std::shared_ptr<tinyxml2::XMLElement> xmlElement;
xmlElement.reset(xmlDoc.createElement()); // <-- error E0304
// Equivalent code, same result:
//tinyxml2::XMLElement* ptr = xmlDoc.createElement();
//xmlElement.reset(ptr);
Error message:
E0304 no instance of overloaded function "std::shared_ptr<_Ty>::reset [with _Ty=tinyxml2::XMLElement]" matches the argument list
argument types are: (tinyxml2::XMLElement *)
object type is: std::shared_ptrtinyxml2::XMLElement
How can I fix it?
Compiler:
- Visual C++ 2022, v.17.12.3
Note: what I get is a compile time error, so I cannot provide any debug information.