最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c++ - Can assign a raw pointer to a `shared_ptr` in a test project only - Stack Overflow

programmeradmin6浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论