Код: Выделить всё
int main()
{
struct test
{
std::string s;
};
std::unique_ptr p = nullptr;
p = std::make_unique("test");
printf("%s\n", p->s);
}
Код: Выделить всё
In file included from /usr/include/c++/14/memory:78,
from struct-pointer.cc:2:
/usr/include/c++/14/bits/unique_ptr.h: In instantiation of ‘std::__detail::__unique_ptr_t std::make_unique(_Args&& ...) [with _Tp = main()::test; _Args = {const char (&)[5]}; __detail::__unique_ptr_t = __detail::__unique_ptr_t]’:
struct-pointer.cc:13:38: required from here
13 | p = std::make_unique("test");
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~
/usr/include/c++/14/bits/unique_ptr.h:1076:30: error: no matching function for call to ‘main()::test::test(const char [5])’
1076 | { return unique_ptr(new _Tp(std::forward(__args)...)); }
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
struct-pointer.cc:6:12: note: candidate: ‘main()::test::test()’
6 | struct test
| ^~~~
struct-pointer.cc:6:12: note: candidate expects 0 arguments, 1 provided
struct-pointer.cc:6:12: note: candidate: ‘main()::test::test(const main()::test&)’
struct-pointer.cc:6:12: note: no known conversion for argument 1 from ‘const char [5]’ to ‘const main()::test&’
struct-pointer.cc:6:12: note: candidate: ‘main()::test::test(main()::test&&)’
struct-pointer.cc:6:12: note: no known conversion for argument 1 from ‘const char [5]’ to ‘main()::test&&’
Код: Выделить всё
struct test foo = { "test" };
Код: Выделить всё
printf("%s\n", foo.s);
Два вопроса: как правильно инициализировать структуру так, чтобы оператор printf выдавал «тест»?
А как инициализировать проверку структуры при использовании unique_ptr вместо локальной переменной?
Подробнее здесь: https://stackoverflow.com/questions/791 ... h-a-struct
Мобильная версия