gpt4 book ai didi

c++ - 如何使用裸新初始化智能点?

转载 作者:搜寻专家 更新时间:2023-10-30 23:58:10 25 4
gpt4 key购买 nike

我正在尝试学习新的 C++ 标准,但在使用智能指针时我遇到了问题。这是我正在编写的一个程序的代码,它不想工作:

#include <iostream>
#include <memory>

template <typename T> class printer
{
public:
printer(T val)
{
value = val;
}

void printvalue()
{
std::cout << "The value is " << val;
std::cin.get();
}


private:
T value;
};

template <typename T> class test
{
public:
test(T value)
{
printer<T> * test = new printer<T>(value);
*printValue = test;
}

void beginTest()
{
printValue.get()->printvalue();
}

private:
std::unique_ptr<printer<T>> printValue;
};

我写的主要功能是这样的:

int main()
{
test<int> t(5);
t.beginTest();
return 0;
}

编译后出现以下错误:二进制“=”: 没有找到接受类型为“printer *”的右手操作数的运算符(或者没有可接受的转换)

this指的是这行代码: *打印值=测试;

我认为 new 即使在这种情况下也能正常工作,不,我可以重载我想的运算符,但我确信我遗漏了什么

注意:我使用的是visual studio 2013编译器

请帮忙

最佳答案

您可以将指针直接传递给 std::unique_ptr 构造器:

test(T value)
: printValue(new printer<T>(value))
{ }

或者您可以在 std::unique_ptr 上调用 reset:

test(T value)
{
printValue.reset(new printer<T>(value));
}

请注意,您不需要使用 get() 来访问 unique_ptr 指向的对象 - 您可以将其视为普通指针:

printValue->printvalue();

关于c++ - 如何使用裸新初始化智能点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21525283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com